<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="客户姓名"
        style="width: 180px"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-input
        v-model="listQuery.phone"
        placeholder="电话号码"
        style="width: 180px"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-button class="filter-item" type="primary" icon="Search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="Plus" @click="handleCreate">
        添加客户
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading..."
      border
      fit
      highlight-current-row
    >
      <el-table-column label="ID" prop="id" align="center" width="60" />
      <el-table-column label="姓名" prop="name" align="center" width="100" />
      <el-table-column label="电话" prop="phone" align="center" width="120" />
      <el-table-column label="邮箱" prop="email" align="center" min-width="160" />
      <el-table-column label="地址" prop="address" align="center" min-width="200" show-overflow-tooltip />
      <el-table-column label="积分" prop="points" align="center" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.points > 1000 ? 'success' : ''">
            {{ scope.row.points }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleUpdate(scope.row)">
            编辑
          </el-button>
          <el-button type="success" size="small" @click="handleUpdatePoints(scope.row)">
            修改积分
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="listQuery.current"
        v-model:page-size="listQuery.size"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑/添加对话框 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '添加客户' : '编辑客户'"
      v-model="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="70px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="temp.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="temp.address" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改积分对话框 -->
    <el-dialog
      title="修改积分"
      v-model="pointsDialogVisible"
      width="400px"
    >
      <el-form
        ref="pointsForm"
        :model="pointsTemp"
        label-position="right"
        label-width="70px"
      >
        <el-form-item label="当前积分">
          <span>{{ pointsTemp.currentPoints }}</span>
        </el-form-item>
        <el-form-item label="变更积分" prop="points">
          <el-input-number
            v-model="pointsTemp.points"
            :min="-pointsTemp.currentPoints"
            placeholder="输入要增加或减少的积分"
          />
          <div class="points-tip">提示：输入正数增加积分，输入负数减少积分</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="pointsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updatePoints">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { createCustomer, deleteCustomer, getCustomerList, updateCustomer, updateCustomerPoints } from '@/api/customer';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';

// 列表数据
const list = ref([])
const total = ref(0)
const listLoading = ref(true)
const listQuery = reactive({
  current: 1,
  size: 10,
  name: '',
  phone: ''
})

// 表单数据
const dialogFormVisible = ref(false)
const dialogStatus = ref('')
const temp = reactive({
  id: undefined,
  name: '',
  phone: '',
  email: '',
  address: '',
  points: 0
})

const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 积分相关
const pointsDialogVisible = ref(false)
const pointsTemp = reactive({
  id: undefined,
  currentPoints: 0,
  points: 0
})

// 获取列表数据
const getList = async () => {
  listLoading.value = true
  try {
    const { data } = await getCustomerList(listQuery)
    list.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('Failed to get customer list:', error)
  } finally {
    listLoading.value = false
  }
}

// 搜索
const handleFilter = () => {
  listQuery.current = 1
  getList()
}

// 分页
const handleSizeChange = (val) => {
  listQuery.size = val
  getList()
}

const handleCurrentChange = (val) => {
  listQuery.current = val
  getList()
}

// 添加
const handleCreate = () => {
  Object.assign(temp, {
    id: undefined,
    name: '',
    phone: '',
    email: '',
    address: '',
    points: 0
  })
  dialogStatus.value = 'create'
  dialogFormVisible.value = true
}

// 编辑
const handleUpdate = (row) => {
  Object.assign(temp, row)
  dialogStatus.value = 'update'
  dialogFormVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该客户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCustomer(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('Failed to delete customer:', error)
    }
  })
}

// 创建数据
const createData = async () => {
  try {
    await createCustomer(temp)
    dialogFormVisible.value = false
    ElMessage.success('添加成功')
    getList()
  } catch (error) {
    console.error('Failed to create customer:', error)
  }
}

// 更新数据
const updateData = async () => {
  try {
    await updateCustomer(temp)
    dialogFormVisible.value = false
    ElMessage.success('更新成功')
    getList()
  } catch (error) {
    console.error('Failed to update customer:', error)
  }
}

// 更新积分
const updatePoints = async () => {
  try {
    const newPoints = pointsTemp.currentPoints + pointsTemp.points
    await updateCustomerPoints(pointsTemp.id, newPoints)
    ElMessage.success('积分更新成功')
    pointsDialogVisible.value = false
    getList()
  } catch (error) {
    console.error('Failed to update customer points:', error)
    ElMessage.error('积分更新失败')
  }
}

// 打开积分修改对话框
const handleUpdatePoints = (row) => {
  pointsTemp.id = row.id
  pointsTemp.currentPoints = row.points || 0
  pointsTemp.points = 0
  pointsDialogVisible.value = true
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  min-width: auto;
}

.filter-container {
  padding-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-item {
  margin-right: 0;
}

.pagination-container {
  margin-top: 30px;
}

.dialog-footer {
  text-align: right;
}

.points-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>